import RPi.GPIO as GPIO
import time
import smbus
import sys
import Adafruit_DHT
# https://www.cnblogs.com/hilary0614/p/dht11.html (dht11可用)
# sudo apt install -y python3-smbus

#BH1750地址
__DEV_ADDR=0x23

#控制字
__CMD_PWR_OFF=0x00  #关机
__CMD_PWR_ON=0x01   #开机
__CMD_RESET=0x07    #重置
__CMD_CHRES=0x10    #持续高分辨率检测
__CMD_CHRES2=0x11   #持续高分辨率模式2检测
__CMD_CLHRES=0x13   #持续低分辨率检测
__CMD_THRES=0x20    #一次高分辨率
__CMD_THRES2=0x21   #一次高分辨率模式2
__CMD_TLRES=0x23    #一次分辨率
__CMD_SEN100H=0x42  #灵敏度100%,高位
__CMD_SEN100L=0X65  #灵敏度100%，低位
__CMD_SEN50H=0x44   #50%
__CMD_SEN50L=0x6A   #50%
__CMD_SEN200H=0x41  #200%
__CMD_SEN200L=0x73  #200%

bus = smbus.SMBus(1)
bus.write_byte(__DEV_ADDR, __CMD_PWR_ON)
bus.write_byte(__DEV_ADDR, __CMD_RESET)
bus.write_byte(__DEV_ADDR, __CMD_SEN100H)
bus.write_byte(__DEV_ADDR, __CMD_SEN100L)
bus.write_byte(__DEV_ADDR, __CMD_PWR_OFF)
def getIlluminance():
    bus.write_byte(__DEV_ADDR, __CMD_PWR_ON)
    bus.write_byte(__DEV_ADDR, __CMD_THRES2)
    time.sleep(0.2)
    res = bus.read_word_data(__DEV_ADDR,0)
    #read_word_data
    res=((res>>8)&0xff)|(res<<8)&0xff00
    res=round(res/(2*1.2),2)
    result="光照强度: "+str(res)+"lx"
    return result

if __name__ == "__main__":
    tim_clk = 1
    sound_really = 0
    # 传感器上电后，要等待1s以越过不稳定状态
    GPIO.setmode(GPIO.BOARD)
    time.sleep(1)
    # 先向传感器发送开始信号，握手-LOW-
    GPIO.setup(16, GPIO.IN)
    while True:

        if GPIO.input(16) == GPIO.LOW:
            sound_status = 1  #低电平有人
        else: sound_status = 0 #

        if((sound_status == 1) and (sound_really == 0)): #一个周期内有一个声音认为有声音 否则低电平太快检测不到
            sound_really = 1

        time.sleep(0.1)
        tim_clk += 1
        if(tim_clk % 10 == 0):
            hum, tem = Adafruit_DHT.read_retry(11, 23)
            if ((tem < 100) and (hum < 100)):
                print('temp:{0:0.1f} C hum:{1:0.1f} %'.format(tem, hum))
            print('sound is: %s \n' % sound_really)
            sound_really = 0
            lux = getIlluminance()
            print('lux is: %s \n' % lux)

